import { queryAdOrder } from "../api";
import { Toast } from "vant";
import { jumpTool } from "@xiaoe/h5-jump-fe";
import { Skynet, LogLevel, LogType } from "@xiaoe/skynet";

//config可选
export const skynet = new Skynet({
  projectName: "transaction",
  projectVersion: "v1.0.0",
  auto: false,
  url: "https://logreport.xiaoeknow.com/ecommerce/report",
});

skynet.turnOn()
//支付回调
export class PayBackHandler {
  constructor(paySuccessUrl, payFailUrl, order,status) {
    this.paySuccessUrl = paySuccessUrl;
    this.payFailUrl = payFailUrl;
    this.order = order;
    this.status = status || '' // 支付状态 success-支付成功；fail-支付失败；confirmBox-跳页面未知支付状态 zkl_check-吱口令未知支付状态
  }
  perform(failCallBack = () => {}) {
    const { trade_id, order_id} = this.order;
    const link_user_id =  this.order?.link_user_id || ''
    const isTourist = this.order?.isTourist
    let params = {}
    if(isTourist){
      params = {
        trade_id,
        order_ids:[order_id],
        select:['pay_state']
      };
    }else{
      params = {
        trade_id,
        order_id,
      };
    }
    skynet.report({
      details: {
        req:{
          message:'调用查询接口场景',
          status:this.status,
          order_id: order_id
        }
      },
      level:  LogLevel.INFO,
      type: LogType.CUSTOM,
    });
    queryAdOrder(params,link_user_id, isTourist)
      .then((data) => {
        const payOrderState = isTourist ? data.list[0].pay_state : data.info.pay_state;
        if (payOrderState === 1 || payOrderState === "SUCCESS") {
            jumpTool.jumpTargetUrl({
              url: decodeURIComponent(this.paySuccessUrl),
              isReplace: true,
            });
        } else {
          return Promise.reject(data);
        }
      })
      .catch((err) => {
        const abortedMsg = sessionStorage.getItem('abortedMsg');
        Toast({ message: abortedMsg || "您的订单未完成支付", duration: 1000 });
        const currentUrl = location.href;

        if (currentUrl == this.payFailUrl) {
          failCallBack();
        } else {
          jumpTool.jumpTargetUrl({
            url: decodeURIComponent(this.payFailUrl),
            isReplace: true,
          });
        }
      });
  }
}
